package com.bjpowernode.controller;

import com.bjpowernode.service.CollectService;
import com.bjpowernode.user.Collect;
import com.bjpowernode.user.Dynamic;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "collect")
public class CollectController {

    @Resource
    private CollectService collectService;

    @RequestMapping(value = "/add.do",produces = "application/text;charset=utf-8")
    @ResponseBody
    public String addCollect(@RequestParam("username") String username,@RequestParam("name") String name, @RequestParam("scid") Integer id){
        if (name.equals(username)){
            return "您不能收藏自己的微博";
        }
        Collect collect = new Collect();
        collect.setUsername(username);
        collect.setScid(id);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(new Date());
        collect.setSctime(time);
        int res = collectService.addCollect(collect);
        if (res == 0){
            int result = collectService.deleteCollect(collect);
            return result == 1 ? "已取消收藏" : "取消收藏失败！";
        }
        return "已收藏";
    }

    @RequestMapping(value = "/selectSelf.do")
    public ModelAndView selectSelf(@RequestParam("name") String name){
        ModelAndView mv = new ModelAndView();
        List<Dynamic> collectList = collectService.findSelfCollect(name);
        mv.addObject("collectList",collectList);
        mv.setViewName("userCollect");
        return mv;
    }

    @RequestMapping(value = "/addSelf.do",produces = "application/text;charset=utf-8")
    @ResponseBody
    public String addSelf(@RequestParam("username") String name,@RequestParam("scid") Integer scid){
        Collect collect = new Collect();
        collect.setUsername(name);
        collect.setScid(scid);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(new Date());
        collect.setSctime(time);
        int res = collectService.addCollect(collect);
        if (res == 0){
            int result = collectService.deleteCollect(collect);
            return result == 1 ? "已取消收藏" : "取消收藏失败！";
        }
        return "已收藏";
    }
}
